package com.yy.wga.mp.module.income.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yy.wga.mp.module.income.entity.pojo.IncomeUpGradeDO;
import com.yy.wga.mp.module.income.entity.pojo.IncomeUserBalanceDO;
import com.yy.wga.mp.module.income.service.IncomeUpGradeService;
import com.yy.wga.mp.module.income.service.IncomeUserBalanceService;
import com.yy.wga.common.core.aop.DistributedLock;
import com.yy.wga.mp.common.utils.mapping.BeansUtils;
import com.yy.wga.mp.module.income.dto.OrderUpGradeCommissionDTO;
import com.yy.wga.mp.module.user.entity.pojo.UserRelationDO;
import com.yy.wga.mp.module.user.enums.EUserGrade;
import com.yy.wga.mp.module.user.service.UserRelationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @Author: gc
 * @Date: 2024/11/12
 * @Description:
 **/
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderUpGradeCommissionManager {

    private final UserRelationService userRelationService;
    private final IncomeUpGradeService incomeUpGradeService;
    private final IncomeUserBalanceService incomeUserBalanceService;

    @Transactional
    @DistributedLock(value = "#order.orderNo")
    public void commission(OrderUpGradeCommissionDTO order) {
        // 已分佣则跳过
        List<IncomeUpGradeDO> incomeOrderList = incomeUpGradeService.list(new LambdaQueryWrapper<IncomeUpGradeDO>()
                .eq(IncomeUpGradeDO::getAppKey, order.getAppKey())
                .eq(IncomeUpGradeDO::getOrderNo, order.getOrderNo()));
        if (!CollectionUtils.isEmpty(incomeOrderList)) {
            log.info("已完成分佣，跳过分佣");
            return;
        }
        // 一定是已结算
        // 查询上级用户
        UserRelationDO userRelationDO = userRelationService.getOne(new LambdaQueryWrapper<UserRelationDO>()
                .eq(UserRelationDO::getAppKey, order.getAppKey())
                .eq(UserRelationDO::getUserId, order.getFromUserId()));
        if (userRelationDO == null) {
            log.info("直通车订单用户没有上级，不需要分佣:{}", order.getFromUserId());
            return;
        }
        Long serverUserId = null;
        Long parentUserId = userRelationDO.getParentUserId();
        // 上级如果就是服务商，则不需要再去查服务商
        if (userRelationDO.getParentGrade().equals(EUserGrade.SERVER_1.getType())) {
            serverUserId = parentUserId;
        } else {
            // 查询上级服务商
            serverUserId = this.getParentUserId(order.getAppKey(), parentUserId);
            // 没有服务商则不分佣
            if (serverUserId == null) {
                return;
            }
        }
        log.info("{}上级服务商:{}", order.getFromUserId(), serverUserId);
        // 分佣
        IncomeUpGradeDO income = BeansUtils.map(order, IncomeUpGradeDO.class);
        income.setParentUserId(parentUserId);
        income.setParentUserConfirm(0);
        income.setUserId(serverUserId);
        income.setStatus(2);
        incomeUpGradeService.save(income);

        // 增加收益
        IncomeUserBalanceDO incomeUserBalance = new IncomeUserBalanceDO();
        incomeUserBalance.setAppKey(order.getAppKey());
        incomeUserBalance.setUserId(serverUserId);
        incomeUserBalance.setSettle(income.getCommissionValue());
        incomeUserBalanceService.incrementIncome(incomeUserBalance);
    }

    /**
     * 查询上级服务商
     * @param appKey
     * @param fromUserId
     * @return
     */
    private Long getParentUserId(String appKey, long fromUserId) {
        long childUserId = fromUserId;
        while (true) {
            UserRelationDO userRelationDO = userRelationService.getOne(new LambdaQueryWrapper<UserRelationDO>()
                    .eq(UserRelationDO::getAppKey, appKey)
                    .eq(UserRelationDO::getUserId, childUserId));
            if (userRelationDO == null) {
                break;
            }
            if (userRelationDO.getParentGrade().equals(EUserGrade.SERVER_1.getType())) {
                return userRelationDO.getParentUserId();
            }
            childUserId = userRelationDO.getParentUserId();
        }
        return null;
    }
}
